<script lang="jsx">
import { defineComponent } from 'vue'

const prefixCls = 'haloe-tabs-tabpane'

function random() {
  return (Math.random() + '').slice(2)
}

export default defineComponent({
  name: 'TabPane',
  inject: ['TabsInstance'],
  props: {
    name: {
      type: String,
    },
    label: {
      type: [String, Function],
      default: '',
    },
    icon: {
      type: String,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    closable: {
      type: Boolean,
      default: null,
    },
    // Tabs 嵌套时，用 tab 区分层级，指向对应的 Tabs 的 name
    tab: {
      type: String,
    },
    // 在 TabPane 使用 v-if 时，并不会按照预先的顺序渲染，这时可设置 index，并从小到大排序
    // 数值需大于 0
    index: {
      type: Number,
    },
    // 4.3.0
    contextMenu: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      prefixCls: prefixCls,
      show: true,
      currentName: this.name,
      id: random(),
    }
  },
  computed: {
    contentStyle() {
      return {
        visibility:
          this.TabsInstance?.exposed?.activeKey?.value !== this.currentName
            ? 'hidden'
            : 'visible',
      }
    },
  },
  methods: {
    updateNav() {
      this.TabsInstance.exposed.updateNav()
    },
    addPane() {
      const paneList = this.TabsInstance.exposed.paneList;
      // if (!root.paneList) root.paneList = []
      paneList.push({
        id: this.id,
        pane: this,
      })
    },
    removePane() {
      const root = this.TabsInstance
      const paneList = root.exposed.paneList;
      if (paneList.length > 0) {
        const index = paneList.findIndex((item) => item.id === this.id)
        paneList.splice(index, 1)
      }
    },
  },
  watch: {
    name(val) {
      this.currentName = val
      this.updateNav()
    },
    label(val) {
      if (typeof val !== 'function') {
        this.updateNav()
      }
    },
    icon() {
      this.updateNav()
    },
    disabled() {
      this.updateNav()
    },
  },
  mounted() {
    this.addPane()
    this.updateNav()
  },
  beforeUnmount() {
    this.removePane()
    this.updateNav()
  },
  render() {
    return (
      <div class={prefixCls} v-show={this.show} style={this.contentStyle}>
        {
          this.$slots.default()
        }
      </div>
    )
  },
})

</script>